package org.sso.common.domian;

import javax.servlet.http.HttpServletRequest;

import org.sso.common.encrypt.RSA;
import org.sso.common.util.IpHelper;
import org.sso.common.util.RandomUtil;

public class Ticket extends TokenBase {
	/* 32 uuid */
	private String uuid;

	private String sign;

	private Token tk;

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	public Token getTk() {
		return tk;
	}

	public void setTk(Token tk) {
		this.tk = tk;
	}

	public String getUuid() {
		return uuid;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

	/**
	 * 有参构造函数
	 *
	 * @param request
	 * @param privateKey
	 *            RSA 私钥（业务系统）
	 */
	public Ticket(HttpServletRequest request, String privateKey) {
		this.uuid = RandomUtil.get32UUID();
		this.setIp(IpHelper.getIpAddr(request));
		this.sign(privateKey);
	}

	/**
	 * 生成签名字节数组
	 * 
	 * @return byte[]
	 */
	public byte[] signByte() {
		StringBuffer sb = new StringBuffer(getUuid());
		sb.append("-").append(this.getIp());
		return sb.toString().getBytes();
	}

	/**
	 * 设置签名 rsaSign
	 * 
	 * @param privateKey
	 *            RSA 私钥（签名）
	 */
	public void sign(String privateKey) {
		try {
			this.sign = RSA.sign(signByte(), privateKey);
		} catch (Exception e) {
			e.printStackTrace();
			throw new SsoException(" AuthToken RSA sign error. ");
		}
	}

	/**
	 * 验证 AuthToken 签名是否合法
	 * 
	 * @param publicKey
	 *            RSA 公钥（验证签名）
	 * @return
	 */
	public Ticket verify(String publicKey) {
		try {
			/**
			 * RSA 验证摘要 是否合法
			 */
			if (RSA.verify(signByte(), publicKey, getSign())) {
				return this;
			}
		} catch (Exception e) {
			// logger.info("verify error.");
			e.printStackTrace();
			throw new SsoException(" AuthToken RSA verify error. ");
		}
		return null;
	}
}
